    //
//  CategoryPageViewController.m
//  ActiveDeck
//
//  Created by BigChicken on 3/3/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CategoryPageViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "AD_Page.h"
#import "AD_Category.h"
#import "AD_Word.h"
#import	"AD_Words.h"
#import "GDataXMLNode.h"
#import "AD_Button.h"
#import "WordSort.h"




@implementation CategoryPageViewController
@synthesize BG_Image;
#define WORDSTART_YLOCATION 20

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

- (GDataXMLElement *)BuildXmlData{
	GDataXMLElement *answerElement = [GDataXMLElement elementWithName:@"Answer"];
	GDataXMLNode *Type = [GDataXMLNode attributeWithName:@"Type" stringValue:@"Categories"];
	GDataXMLNode *Page = [GDataXMLNode attributeWithName:@"Page" stringValue:[NSString stringWithFormat:@"%d",pageOB.pageID]];
	[answerElement addChild:Type];
	[answerElement addChild:Page];

	for(AD_Category *catOB in categories)
	{
		GDataXMLElement *catElement = [GDataXMLElement elementWithName:@"Category"];
		GDataXMLNode *cateID = [GDataXMLNode attributeWithName:@"ID" stringValue:[NSString stringWithFormat:@"%d", catOB.Value]];
		[catElement addChild:cateID];
		
		for(NSNumber *item in catOB.bucket)
		{
			GDataXMLElement *itemElement = [GDataXMLElement elementWithName:@"Item"];
			GDataXMLNode *itemID = [GDataXMLNode attributeWithName:@"ID" stringValue:[item stringValue]];
			[itemElement addChild:itemID];
			[catElement addChild:itemElement];
		}
		
		[answerElement addChild:catElement];
	}
	
	return answerElement;	
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	NSLog(@"Loading CategoryView");
    NSLog(@"BGImage = %@", pageOB.imageBG);
 
    //BG_Image.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:[[pageOB.mut_Arr_Images objectAtIndex:0] imagePath]]];
    BG_Image.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:pageOB.imageBG]];
    
    [self addImage];

	//BG_Image.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:pageOB.imageBG]];
    
    buttonsSet = [[NSMutableArray alloc]init];
    [self initializeSort];
    [self AddButton];
    [super viewDidLoad];
}

- (void)reset
{
    for (WordSort *ws in wvArray)
        [ws removeFromSuperview];
    
    for (UIImageView *ccImage in catCapImage)
        [ccImage removeFromSuperview];
    
    for (UIImageView *ceImage in catEdgeImage)
        [ceImage removeFromSuperview];
    
    for (AD_Category *adCat in pageOB.mut_Arr_Category)
    {
        for (NSNumber *nb in adCat.bucket)
            adCat.Top += WORDSTART_YLOCATION;
        
        [adCat.bucket removeAllObjects];
    }

    
    [wordsList release];
    [categories release];
    [catCapImage release];
    [catEdgeImage release];
    [wvArray release];
    
    [self initializeSort];
    
    [self.view bringSubviewToFront:Bar_Container];
}

- (void)initializeSort
{
    AD_Words *wordsConfig = (AD_Words*)[pageOB.mut_Arr_Words objectAtIndex:0];
	startPoints =[[NSArray alloc] initWithArray:wordsConfig.mut_Arr_StartPoistion];
    
    leftCount = wordsConfig.count;
	wordsList = [[NSMutableArray alloc] initWithArray:wordsConfig.mut_Arr_Words];
	catCapImage = [[NSMutableArray alloc]init];
	catEdgeImage = [[NSMutableArray alloc]init];
	categories = [[NSMutableArray alloc]init];
	wvArray = [[NSMutableArray alloc]init];
    
    noTouch = FALSE;
    submitPressed = FALSE;
	
	for(AD_Category *adCat in pageOB.mut_Arr_Category)
	{
		NSLog(@"catBucketImage %@", adCat.bucketCap);
		UIImage *capImg = [UIImage imageWithData:[NSData dataWithContentsOfFile:adCat.bucketCap]];
		UIImageView *catBuckCap = [[UIImageView alloc] initWithImage:capImg];
		
		UIImage *edgeImg = [UIImage imageWithData:[NSData dataWithContentsOfFile:adCat.bucketEdge]];
		UIImageView *catBuckEdge = [[UIImageView alloc] initWithImage:edgeImg];
		
		catBuckCap.center = CGPointMake(adCat.Left + adCat.bcWidth /2 , adCat.Top + adCat.bcHeight /2);
		catBuckEdge.center = CGPointMake(adCat.beLeft + adCat.beWidth /2 , adCat.beTop + adCat.beHeight /2);
        
		catBuckEdge.frame = CGRectMake(catBuckEdge.frame.origin.x, catBuckEdge.frame.origin.y, adCat.beWidth, adCat.beHeight);
        
		[self.view addSubview:catBuckCap];
		[self.view addSubview:catBuckEdge];
		
		[catCapImage addObject:catBuckCap];
		[catEdgeImage addObject:catBuckEdge];
		[categories addObject:adCat];
		
		[catBuckCap release];
		[catBuckEdge release];
		
		if(adCat.Top > UpperLimited)
			UpperLimited = adCat.Top + 50;
	}
	
	
	int i = 0;
	
	for(AD_Word *word in wordsList)
	{
		if(i >= [startPoints count])
		{
			i--;
			break;
		}
        
		[self sortViewSetup:word CGLocation:[[startPoints objectAtIndex:i++]CGPointValue]];
	}
        for(;i >=0; i--)
        {
            //NSLog(@"wordIndex=%d", i);
            if(i < [wordsList count])
                [wordsList removeObjectAtIndex:i];   
        }
}

- (void)AddButton
{
	int i=0;
	for(AD_Button *multiButton in pageOB.mut_Arr_Button)
	{
		UIImage *offImage = [UIImage imageWithData:[NSData dataWithContentsOfFile:multiButton.imageOff]];
		UIImage *onImage = [UIImage imageWithData:[NSData dataWithContentsOfFile:multiButton.imageOn]];
		CGRect buttonFrame = CGRectMake(multiButton.left, multiButton.top, multiButton.width, multiButton.height);
		NSArray *condition = [multiButton.Condition componentsSeparatedByString:@"=="];
        
		UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
		[newButton setFrame:buttonFrame];
		[newButton setTag:i++];
		[newButton setBackgroundImage:offImage forState:UIControlStateNormal];
		[newButton setBackgroundImage:onImage forState:UIControlStateHighlighted];
		[newButton setBackgroundImage:onImage forState:UIControlStateSelected];
		[newButton addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
		
        for(AD_Action *action in multiButton.actions){
            if([action isKindOfClass:[Action_Submit class]] || [action isKindOfClass:[Action_Next class]]){
                newButton.enabled = TRUE;
                Bt_Submit = newButton;
                break;
            }
        }
//		if([multiButton.buttonType isEqualToString:@"Submit"] || [multiButton.buttonType isEqualToString:@"Next"])
//		{
//			newButton.enabled = TRUE;
//			Bt_Submit = newButton;
//		}
		
        [newButton setHidden:[self setCondition:condition]];
		[buttonsSet addObject:newButton]; //Test memory location 
		[self.view	addSubview:newButton]; //Test memory removed
	}
	
}


-(void)buttonPress:(id)sender
{
	UIButton *pressButton = (UIButton *)sender;
	AD_Button *multiButton = (AD_Button*)[pageOB.mut_Arr_Button objectAtIndex:pressButton.tag];
	
//	NSLog(@"Button Type %@", multiButton.buttonType);
    
    for(AD_Action* action in multiButton.actions){
        if ([action isKindOfClass:[Action_Submit class]]) {
            [self appendUserData:[self BuildXmlData]];
            [self submitUserData];
            submitPressed = TRUE;
            NSLog(@"Submit the user data");
            for (UIButton* bt_one in buttonsSet) 
                bt_one.enabled = FALSE;
        }else if ([action isKindOfClass:[Action_Next class]]) {
            NSLog(@"Go to the next page");
            [self appendUserData:[self BuildXmlData]];
            submitPressed = TRUE;
            if(pageOB.grade.hasInstantFeedback){
                [self addInstantFeedback];
            } else {
                [self loadNextPage];
            }
        }else if ([action isKindOfClass:[Action_Reset class]]){
            NSLog(@"Reset the Selection");
            [self reset];
        }else if ([action isKindOfClass:[Action_GoTo class]]) {
            Action_GoTo* gt = (Action_GoTo*)action;
            NSLog(@"Go To Special Session");
            [self appendUserData:[self BuildXmlData]];
            [self GoToSection:gt.section
                    NewPageID:gt.page];
        }
    }
	
//	if ([multiButton.buttonType isEqualToString:@"Submit"]) {
//		[self appendUserData:[self BuildXmlData]];
//		[self submitUserData];
//        submitPressed = TRUE;
//		NSLog(@"Submit the user data");
//		for (UIButton* bt_one in buttonsSet) 
//            bt_one.enabled = FALSE;
//    }else if ([multiButton.buttonType isEqualToString:@"Next"]) {
//		NSLog(@"Go to the next page");
//		[self appendUserData:[self BuildXmlData]];
//        submitPressed = TRUE;
//        if(pageOB.grade.hasInstantFeedback){
//            [self addInstantFeedback];
//        } else {
//            [self loadNextPage];
//        }
//	}else if ([multiButton.buttonType isEqualToString:@"Reset"]){
//        NSLog(@"Reset the Selection");
//        [self reset];
//    }else if ([multiButton.buttonType isEqualToString:@"GoTo"]) {
//        NSLog(@"Go To Special Session");
//        [self appendUserData:[self BuildXmlData]];
//        [self GoToSection:multiButton.section
//                NewPageID:multiButton.page];
//    }
	
}


-(void)sortViewSetup:(AD_Word *)word
		  CGLocation:(CGPoint)CGLocation
{
	WordSort *wsView = [[WordSort alloc] init:word.text sPoint:CGLocation];
	wsView.center = CGLocation;
	wsView.wID = word.wordID;
	
	[wsView ReturnDisplaySetup];
	[self.view addSubview:wsView];
	
	[wvArray addObject:wsView];;
	
	[wsView release]; //Memory Testing
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
	
	UITouch *touch = [touches anyObject];
	
	CGPoint tp = [touch locationInView:self.view];
	
	if (tp.y > UpperLimited || submitPressed) 
	{
		noTouch = TRUE;
		return;
	}
	
	int i = 0;	
	for (WordSort *wsV in wvArray)
	{
		if([touch view] != wsV)
			i++;
		else
			break;
		
		if (i >= [wvArray count]) {
			return;
		}
	}
	if([wvArray count] > 0)
    {
        wordSortView = [wvArray objectAtIndex:i];
        [wordSortView SelectedDisplaySetup];
	
        CGPoint touchPoint = [touch locationInView:self.view];
        [self animateFirstTouchAtPoint:touchPoint];
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (submitPressed) {
        return;
    }
	
	UITouch *touch = [touches anyObject];
	
	CGPoint tp = [touch locationInView:self.view];
	
	
	if (tp.y > UpperLimited && noTouch) 
		return;
	
    
	
	if([touch view] == wordSortView)
	{
		CGPoint location = [touch locationInView:self.view];
		wordSortView.center = location;
		return;
	}
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];

	
	if(noTouch)
	{
		noTouch = FALSE;
		return;
	}
	UITouch *touch = [touches anyObject];
	
	
	if([touch view] == wordSortView)
	{
		self.view.userInteractionEnabled = NO;
		[self animateWordSortViewToCenter];
        [self.view bringSubviewToFront:Bar_Container];
	}
}

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
	wordSortView.center = self.view.center;
	wordSortView.transform = CGAffineTransformIdentity;
}

- (void) animateFirstTouchAtPoint:(CGPoint)touchPoint
{
#define GROW_ANIMATION_DURATION_SECONDS 0.2
#define SHRINK_ANIMATION_DURATION_SECONDS 0.1
	
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:GROW_ANIMATION_DURATION_SECONDS];
	[UIView	setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(growAnimationDidStop:finished:context:)];
	CGAffineTransform transform = CGAffineTransformMakeScale(1.2, 1.2);
	wordSortView.transform = transform;
	[UIView commitAnimations];
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:GROW_ANIMATION_DURATION_SECONDS + SHRINK_ANIMATION_DURATION_SECONDS];
	wordSortView.center = touchPoint;
	[UIView commitAnimations];
}

- (void) growAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void*)context
{
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:SHRINK_ANIMATION_DURATION_SECONDS];
	wordSortView.transform = CGAffineTransformMakeScale(1.1, 1.1);
	[UIView commitAnimations];
}


-(void)BMove:(int)index
{
	UIImageView *beckTop = (UIImageView *)[catCapImage objectAtIndex:index];
	UIImageView *beckEdge = (UIImageView *)[catEdgeImage objectAtIndex:index];
	
	beckTop.center = CGPointMake(beckTop.center.x, beckTop.center.y - WORDSTART_YLOCATION);
	beckEdge.frame = CGRectMake(beckEdge.frame.origin.x, beckEdge.frame.origin.y - WORDSTART_YLOCATION , beckEdge.frame.size.width, beckEdge.frame.size.height + WORDSTART_YLOCATION);
}

-(void)animateWordSortViewToCenter
{
	
	CGPoint newpoint = wordSortView.oPoint;
		
	int i = 0;
	for (AD_Category *catOB in categories)
	{
		if(wordSortView.center.x > catOB.Left && wordSortView.center.x < (catOB.Left + catOB.Width) && wordSortView.center.y > (catOB.Top - catOB.Height) && wordSortView.center.y > UpperLimited)
		{
			wordSortView.oPoint = CGPointMake(catOB.Left + catOB.Width/2, catOB.Top + catOB.Height - catOB.bcHeight + (WORDSTART_YLOCATION / 2));
			catOB.Top -= WORDSTART_YLOCATION;
			[catOB.bucket addObject:[NSNumber numberWithInteger:wordSortView.wID]];
			[self BMove:i];
		}
		
		if (catOB.Top < UpperLimited)
			UpperLimited = catOB.Top;
		i++;
	}
	


	
	CALayer *wsLayer = wordSortView.layer;
	
	CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
	bounceAnimation.removedOnCompletion = NO;
	
	CGFloat animationDuration = 0.5;
	
	CGMutablePathRef thePath = CGPathCreateMutable();
	
	CGFloat midX = wordSortView.oPoint.x;
	CGFloat midY = wordSortView.oPoint.y;
	CGFloat originalOffsetX = wordSortView.center.x - midX;
	CGFloat originalOffsetY = wordSortView.center.y - midY;
	CGFloat offsetDivider = 100.0;
	
	BOOL stopBounching = NO;
	
	CGPathMoveToPoint(thePath, NULL, wordSortView.center.x, wordSortView.center.y);
	CGPathAddLineToPoint(thePath, NULL, midX, midY);
	
	while (stopBounching != YES) {
		CGPathAddLineToPoint(thePath, NULL, midX + originalOffsetX/offsetDivider, midY + originalOffsetY/offsetDivider);
		CGPathAddLineToPoint(thePath, NULL, midX, midY);
		
		offsetDivider +=4;
		animationDuration += 1/ offsetDivider;
		if((abs(originalOffsetX/offsetDivider)<6) && (abs(originalOffsetY/offsetDivider) < 6))
		{
			stopBounching = YES;
		}
	}
	
	bounceAnimation.path = thePath;
	bounceAnimation.duration = animationDuration;
	CGPathRelease(thePath);
	
	CABasicAnimation *transformAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
	transformAnimation.removedOnCompletion = YES;
	transformAnimation.duration = animationDuration;
	transformAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
	
	CAAnimationGroup *theGroup = [CAAnimationGroup animation];
	
	theGroup.delegate = self;
	theGroup.duration = animationDuration;
	theGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
	
	theGroup.animations = [NSArray arrayWithObjects:bounceAnimation, transformAnimation, nil];
	
	[wsLayer addAnimation:theGroup forKey:@"animateWordSortViewToCenter"];
	
	if (newpoint.x != wordSortView.oPoint.x && newpoint.y != wordSortView.oPoint.y )
	{
		if(leftCount > 0 && [wordsList count] > 0 )
		{
			AD_Word *nextWord = [wordsList objectAtIndex:0];
			[self sortViewSetup:nextWord CGLocation:newpoint];
			[wordsList removeObjectAtIndex:0];
			leftCount--;
		}
		
	}
	[wordSortView ReturnDisplaySetup];
	wordSortView.transform = CGAffineTransformIdentity;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
	wordSortView.transform = CGAffineTransformIdentity;
	self.view.userInteractionEnabled = YES;
}



- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    
    [startPoints release];
    [catCapImage release];
    [catEdgeImage release];
    [categories release];
    [buttonsSet release];
    [wordsList release];
    [BG_Image release];
    [super dealloc];
}


@end
